<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Progressive Play Server
 * Connect and parse REFRESH packets from Soldat servers.
 * /libraries/Soldat_refresh.php
 * By: Yukwunhang
 */
class Soldat_refresh
{	
	// Get info
	function refresh()
	{
		// Load Server Settings
		$CI =& get_instance();
		$CI->config->load('soldat_server', TRUE, TRUE);
		$server_cfg = $CI->config->item('soldat_server');
		
		// Open connection
		$sock = @fsockopen($server_cfg['ip'], $server_cfg['port'], $errstr, $errnum, 1);
		if(!$sock){
			return FALSE;
		}
		$buffer = '';
		// Send password
		fputs($sock, $server_cfg['password']."\r\n");
		
		fputs($sock, "REFRESH\r\n");
		while( $buffer != "REFRESH" )
		{
			$buffer = trim(fgets($sock, 1024));
			// Break connection if password is incorrect
			if (eregi("password", $buffer))
			{
				return FALSE;
			}
			if ( !$buffer ) continue;
			else if( $buffer == "REFRESH") break;
		}
		
		$info = $this->GetSoldatInfo($sock);
		
		fclose($sock);
		
		return $info;
		
	}
	
	/**
	 * Parse REFRESH packets
	 * @return array of player info
	 * @param object $sock
	 */
	public function GetSoldatInfo(&$sock)
	{
        if (!$sock) return false;
        $info = array(
            'gamemode'    => 0,
            'teammode'    => false,
            'pointmode'    => false,
            'players'     => 0,
            'spectators'     => 0,
            'map'        => '',
            'timelimit'    => 0,
            'currenttime'    => 0,
            'timeleft'    => 0,
            'limit'        => 0,
            'player'    => array(),
            'spectator'    => array(),
            'team'        => array()
        );
 
        // Temporary array for players
        $players = array();
        for ($i = 0; $i < 32; $i++) {
            $players[$i] = array(
                'name'         => '',
                'ip'         => '',
                'id'         => 0,
                'kills'        => 0,
                'deaths'    => 0,
                'team'        => 0,
                'ping'        => 0
            );
        }
 
        // Get player names
        for ($i = 0; $i < 32; $i++) {
            $data = fread($sock, 25);
            $len = ord($data[0]);
            $players[$i]['name'] = substr($data, 1, $len);
        }
 
        // Get player teams
        for ($i = 0; $i < 32; $i++) {
            $data = fread($sock, 1);
            $players[$i]['team'] = ord($data);
        }
 
        // Get player kills
        for ($i = 0; $i < 32; $i++) {
            $data = unpack("v", fread($sock, 2));
            $kills = $data[1];
            $players[$i]['kills'] = $kills;
        }
 
        // Get player deaths
        for ($i = 0; $i < 32; $i++) {
            $data = unpack("v", fread($sock, 2));
            $deaths = $data[1];
            $players[$i]['deaths'] = $deaths;
        }
 
        // Get player pings
        for ($i = 0; $i < 32; $i++) {
            $data = fread($sock, 1);
            $players[$i]['ping'] = ord($data);
        }
 
        // Get player IDs
        for ($i = 0; $i < 32; $i++) {
            $data = fread($sock, 1);
            $players[$i]['id'] = ord($data);
        }
 
        // Get player IPs
        for ($i = 0; $i < 32; $i++) {
            $data = unpack("N", fread($sock, 4));
            $players[$i]['ip'] = long2ip($data[1]);
        }
 
        // Get team scores
        for ($i = 1; $i < 5; $i++) {
            $data = unpack("v", fread($sock, 2));
            $score = $data[1];
            $info['team'][$i] = $score;
        }
 
        // Get map name
        $data = fread($sock, 17);
        $len = ord($data[0]);
        $info['map'] = substr($data, 1, $len);
 
        // Get time limit & current time, and form timeleft
        $data = unpack("V", fread($sock, 4));
        $timelimit = $data[1];
        $info['timelimit'] = $timelimit;
        $data = unpack("V", fread($sock, 4));
        $currenttime = $data[1];
        $info['currenttime'] = $timelimit - $currenttime;
 
        $timeleft = $currenttime;
        $temp = (floor($timeleft / 60) % 60);
        $info['timeleft'] = floor($timeleft / 3600) . ':' . ($temp < 10 ? '0' : '') . $temp;
 
        // Get kill limit
        $data = unpack("v", fread($sock, 2));
        $limit = $data[1];
        $info['limit'] = $limit;
 
        // Get gamestyle
        $data = fread($sock, 1);
        $gamestyle = ord($data);
        $info['gamemode'] = $gamestyle;
        if ($gamestyle == 2 || $gamestyle == 3 || $gamestyle == 5 || $gamestyle == 6) {
            $info['teammode'] = true;
            if ($gamestyle != 2) { $info['pointmode'] = true; }
        }
        if ($gamestyle != 2) {
            if ($gamestyle != 3 && $gamestyle != 5) {
                unset($info['team'][1]);
                unset($info['team'][2]);
            }
            unset($info['team'][3]);
            unset($info['team'][4]);
        }
 
        foreach ($players as $player) {
            if ($player['team'] < 5) {
                $info['players']++;
                $info['player'][] = $player;
            }
            else if ($player['team'] == 5) {
                $info['spectators']++;
                $info['spectator'][] = $player;
            }
        }
 
        return $info;
    }
	
}

/*
 * End of file
 */